﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;

namespace AutoSubmit.Lib
{
    public static class WebDriverExtension
    {
        public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(timeoutInSeconds * 1000));
                try
                {
                    IWebElement current = wait.Until(drv => drv.FindElement(by));
                }
                catch
                {
                    driver.Navigate().Refresh();
                    wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(timeoutInSeconds * 1000));
                    try
                    {
                        wait.Until(drv => drv.FindElement(by));
                    }
                    catch
                    {
                        return null;
                    }
                }

            }
            return driver.FindElement(by);
        }


        public static ReadOnlyCollection<IWebElement> FindElements(this IWebDriver driver, By by, int timeoutInSeconds)
        {
            if (timeoutInSeconds > 0)
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(timeoutInSeconds * 1000));
                try
                {
                    wait.Until(drv => drv.FindElements(by));
                }
                catch
                {
                    driver.Navigate().Refresh();
                    wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(timeoutInSeconds * 1000));
                    try
                    {
                        wait.Until(drv => drv.FindElements(by));
                    }
                    catch
                    {
                        return null;
                    }
                }

            }
            return driver.FindElements(by);
        }
    }
}
